<template>
  <div class="logistics-info-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>物流信息管理</span>
          <el-button type="primary" @click="handleRefresh">刷新</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="物流单号">
          <el-input v-model="searchForm.trackingNo" placeholder="请输入物流单号" clearable />
        </el-form-item>
        <el-form-item label="物流状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="已发货" value="shipped" />
            <el-option label="运输中" value="in_transit" />
            <el-option label="已签收" value="delivered" />
            <el-option label="异常" value="exception" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 物流信息列表 -->
      <el-table :data="filteredLogisticsInfo" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="orderNo" label="订单编号" width="160" />
        <el-table-column prop="trackingNo" label="物流单号" width="160" />
        <el-table-column prop="logisticsCompany" label="物流公司" width="120" />
        <el-table-column label="物流状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentLocation" label="当前位置" show-overflow-tooltip />
        <el-table-column prop="estimatedDelivery" label="预计送达" width="120" />
        <el-table-column prop="updateTime" label="更新时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetails(row)">查看详情</el-button>
            <el-button type="warning" size="small" @click="handleUpdateStatus(row)">更新状态</el-button>
            <el-button type="info" size="small" @click="handleViewRoute(row)">查看轨迹</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 物流详情对话框 -->
    <el-dialog
      v-model="detailsDialogVisible"
      title="物流详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ currentLogistics.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="物流单号">{{ currentLogistics.trackingNo }}</el-descriptions-item>
        <el-descriptions-item label="物流公司">{{ currentLogistics.logisticsCompany }}</el-descriptions-item>
        <el-descriptions-item label="物流状态">
          <el-tag :type="getStatusType(currentLogistics.status)">
            {{ getStatusLabel(currentLogistics.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="发货时间">{{ currentLogistics.shipTime }}</el-descriptions-item>
        <el-descriptions-item label="预计送达">{{ currentLogistics.estimatedDelivery }}</el-descriptions-item>
        <el-descriptions-item label="当前位置" :span="2">{{ currentLogistics.currentLocation }}</el-descriptions-item>
        <el-descriptions-item label="收件人" :span="2">{{ currentLogistics.recipient }}</el-descriptions-item>
        <el-descriptions-item label="收件地址" :span="2">{{ currentLogistics.deliveryAddress }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentLogistics.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailsDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="更新物流状态"
      width="400px"
    >
      <el-form :model="statusForm" :rules="statusRules" ref="statusFormRef" label-width="80px">
        <el-form-item label="物流状态" prop="status">
          <el-select v-model="statusForm.status" placeholder="请选择物流状态">
            <el-option label="已发货" value="shipped" />
            <el-option label="运输中" value="in_transit" />
            <el-option label="已签收" value="delivered" />
            <el-option label="异常" value="exception" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前位置" prop="currentLocation">
          <el-input v-model="statusForm.currentLocation" placeholder="请输入当前位置" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="statusForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitStatus">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 物流轨迹对话框 -->
    <el-dialog
      v-model="routeDialogVisible"
      title="物流轨迹"
      width="600px"
    >
      <el-timeline>
        <el-timeline-item
          v-for="(item, index) in currentRoute"
          :key="index"
          :timestamp="item.time"
          :type="index === 0 ? 'primary' : ''"
          :color="index === 0 ? '#0bbd87' : ''"
        >
          {{ item.location }} - {{ item.description }}
        </el-timeline-item>
      </el-timeline>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="routeDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getLogisticsList, 
  getLogisticsDetail, 
  updateLogisticsStatus, 
  getLogisticsRoutes,
  addLogisticsRoute,
  deleteLogistics
} from '../api/logistics.js'

// 数据
const loading = ref(false)
const logisticsInfo = ref([])
const searchForm = reactive({
  orderNo: '',
  trackingNo: '',
  status: '',
  dateRange: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情对话框
const detailsDialogVisible = ref(false)
const currentLogistics = ref({})

// 状态更新对话框
const statusDialogVisible = ref(false)
const statusFormRef = ref()
const statusForm = reactive({
  id: null,
  status: '',
  currentLocation: '',
  remark: ''
})

// 状态更新表单验证
const statusRules = {
  status: [
    { required: true, message: '请选择物流状态', trigger: 'change' }
  ],
  currentLocation: [
    { required: true, message: '请输入当前位置', trigger: 'blur' }
  ]
}

// 轨迹对话框
const routeDialogVisible = ref(false)
const currentRoute = ref([])

// 模拟数据
const mockLogisticsInfo = [
  {
    id: 1,
    orderNo: 'ORD20241201001',
    trackingNo: 'SF1234567890',
    logisticsCompany: '顺丰速运',
    status: 'in_transit',
    currentLocation: '北京市朝阳区配送中心',
    estimatedDelivery: '2024-12-03',
    updateTime: '2024-12-01 15:30:00',
    shipTime: '2024-12-01 10:00:00',
    recipient: '张三',
    deliveryAddress: '北京市朝阳区xxx街道xxx号',
    remark: '客户要求工作日配送'
  },
  {
    id: 2,
    orderNo: 'ORD20241201002',
    trackingNo: 'YT9876543210',
    logisticsCompany: '圆通速递',
    status: 'shipped',
    currentLocation: '上海市浦东新区分拣中心',
    estimatedDelivery: '2024-12-04',
    updateTime: '2024-12-01 14:20:00',
    shipTime: '2024-12-01 11:30:00',
    recipient: '李四',
    deliveryAddress: '上海市浦东新区xxx街道xxx号',
    remark: ''
  },
  {
    id: 3,
    orderNo: 'ORD20241130001',
    trackingNo: 'ZTO5555666677',
    logisticsCompany: '中通快递',
    status: 'delivered',
    currentLocation: '已签收',
    estimatedDelivery: '2024-12-01',
    updateTime: '2024-12-01 09:15:00',
    shipTime: '2024-11-29 15:00:00',
    recipient: '王五',
    deliveryAddress: '广州市天河区xxx街道xxx号',
    remark: '已签收'
  }
]

// 模拟轨迹数据
const mockRoutes = {
  1: [
    { time: '2024-12-01 10:00:00', location: '深圳发货点', description: '快件已发出' },
    { time: '2024-12-01 12:30:00', location: '广州转运中心', description: '快件到达转运中心' },
    { time: '2024-12-01 15:30:00', location: '北京市朝阳区配送中心', description: '快件到达目的地，准备配送' }
  ],
  2: [
    { time: '2024-12-01 11:30:00', location: '上海发货点', description: '快件已发出' },
    { time: '2024-12-01 14:20:00', location: '上海市浦东新区分拣中心', description: '快件正在分拣中' }
  ],
  3: [
    { time: '2024-11-29 15:00:00', location: '深圳发货点', description: '快件已发出' },
    { time: '2024-11-30 08:00:00', location: '广州转运中心', description: '快件到达转运中心' },
    { time: '2024-12-01 02:30:00', location: '广州分拨中心', description: '快件正在派送中' },
    { time: '2024-12-01 09:15:00', location: '广州市天河区', description: '快件已签收' }
  ]
}

// 状态映射函数
const getStatusType = (status) => {
  const statusMap = {
    'shipped': 'primary',
    'in_transit': 'warning',
    'delivered': 'success',
    'exception': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusLabel = (status) => {
  const labelMap = {
    'shipped': '已发货',
    'in_transit': '运输中',
    'delivered': '已签收',
    'exception': '异常'
  }
  return labelMap[status] || status
}

// 计算属性：过滤后的物流信息列表
const filteredLogisticsInfo = computed(() => {
  let result = logisticsInfo.value

  // 搜索过滤
  if (searchForm.orderNo) {
    result = result.filter(item => 
      item.orderNo.toLowerCase().includes(searchForm.orderNo.toLowerCase())
    )
  }
  if (searchForm.trackingNo) {
    result = result.filter(item => 
      item.trackingNo.toLowerCase().includes(searchForm.trackingNo.toLowerCase())
    )
  }
  if (searchForm.status) {
    result = result.filter(item => item.status === searchForm.status)
  }
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const [startDate, endDate] = searchForm.dateRange
    result = result.filter(item => {
      const itemDate = item.shipTime.split(' ')[0]
      return itemDate >= startDate && itemDate <= endDate
    })
  }

  // 分页
  total.value = result.length
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 方法
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除物流信息"${row.trackingNo}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteLogistics(row.id)
    if (response.success) {
      ElMessage.success('删除成功')
      getLogisticsListData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除物流信息失败:', error)
      ElMessage.error('删除物流信息失败，请稍后重试')
    }
  }
}

const getLogisticsListData = async () => {
  try {
    loading.value = true
    const response = await getLogisticsList({
      page: currentPage.value,
      pageSize: pageSize.value,
      orderNumber: searchForm.orderNumber,
      logisticsNumber: searchForm.logisticsNumber,
      status: searchForm.status,
      startDate: searchForm.dateRange ? searchForm.dateRange[0] : '',
      endDate: searchForm.dateRange ? searchForm.dateRange[1] : ''
    })
    
    if (response.success) {
      logisticsList.value = response.data.list || response.data || []
      total.value = response.data.total || response.total || logisticsList.value.length
    } else {
      ElMessage.error(response.message || '获取物流信息失败')
      // 回退到模拟数据
      logisticsList.value = mockLogisticsInfo
      total.value = mockLogisticsInfo.length
    }
  } catch (error) {
    console.error('获取物流信息失败:', error)
    ElMessage.error('获取物流信息失败，请稍后重试')
    // 回退到模拟数据
    logisticsList.value = mockLogisticsInfo
    total.value = mockLogisticsInfo.length
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleReset = () => {
  searchForm.orderNo = ''
  searchForm.trackingNo = ''
  searchForm.status = ''
  searchForm.dateRange = ''
  currentPage.value = 1
}

const handleRefresh = () => {
  getLogisticsList()
  ElMessage.success('刷新成功')
}

const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const handleViewDetails = (row) => {
  currentLogistics.value = row
  detailsDialogVisible.value = true
}

const handleUpdateStatus = (row) => {
  statusForm.id = row.id
  statusForm.status = row.status
  statusForm.currentLocation = row.currentLocation
  statusForm.remark = ''
  statusDialogVisible.value = true
}

const handleSubmitStatus = async () => {
  statusFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await updateLogisticsStatus(statusForm.id, statusForm)
        if (response.success) {
          statusDialogVisible.value = false
          ElMessage.success('物流状态更新成功')
          getLogisticsListData()
        } else {
          ElMessage.error(response.message || '物流状态更新失败')
        }
      } catch (error) {
        console.error('更新物流状态失败:', error)
        ElMessage.error('更新物流状态失败，请稍后重试')
      }
    }
  })
}

const handleViewRoute = async (row) => {
  try {
    // 获取物流轨迹
    const response = await getLogisticsRoutes(row.id)
    if (response.success) {
      currentRoute.value = response.data || []
    } else {
      // 回退到模拟数据
      currentRoute.value = mockRoutes[row.id] || []
    }
  } catch (error) {
    console.error('获取物流轨迹失败:', error)
    ElMessage.error('获取物流轨迹失败')
    // 回退到模拟数据
    currentRoute.value = mockRoutes[row.id] || []
  }
  routeDialogVisible.value = true
}

// 生命周期
onMounted(() => {
  getLogisticsListData()
})
</script>

<style scoped>
.logistics-info-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>